package dingyunchi.job.dao.impl;

import dingyunchi.job.dao.ScoreDao;
import dingyunchi.job.entity.Score;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class ScoreDaoImpl implements ScoreDao {
    private final JdbcTemplate jdbcTemplate;

    public ScoreDaoImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public Score save(Score score) {
        String sql = "INSERT INTO score (student_id, course_id, score, exam_date) VALUES (?,?,?,?)";
        jdbcTemplate.update(sql, score.getStudentId(), score.getCourseId(), score.getScore(), score.getExamDate());
        Long id = jdbcTemplate.queryForObject("SELECT LAST_INSERT_ID()", Long.class);
        score.setId(id);
        return score;
    }

    @Override
    public Score findById(Long id) {
        String sql = "SELECT * FROM score WHERE id =?";
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Score.class), id);
    }

    @Override
    public List<Score> findAll() {
        String sql = "SELECT * FROM score";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Score.class));
    }

    @Override
    public void update(Score score) {
        String sql = "UPDATE score SET student_id =?, course_id =?, score =?, exam_date =? WHERE id =?";
        jdbcTemplate.update(sql, score.getStudentId(), score.getCourseId(), score.getScore(), score.getExamDate(), score.getId());
    }

    @Override
    public void delete(Long id) {
        String sql = "DELETE FROM score WHERE id =?";
        jdbcTemplate.update(sql, id);
    }
}